package com.streaminggbs.common.config;

import com.alibaba.fastjson.JSONObject;
import com.streaminggbs.common.utils.SpringUtil;
import com.streaminggbs.interfaces.Gb28181Service;
import com.streaminggbs.service.Gb28181ServiceImpl;
import com.streaminggbs.service.SysParamSetServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.net.URI;

@Component
@ClientEndpoint
@Slf4j
public class DeviceAlarmWebsocketConfig {

    // 初始化监听对象
    public static Integer retryNum = 0;
    @Value("${device.alarm.ws.url}")
    public  String deviceStatusWsUrl;


    public static String deviceStatusWsUrl2;
    public void startJob() {
        deviceStatusWsUrl2 = String.format(deviceStatusWsUrl,SpringUtil.getBean(SysParamSetServiceImpl.class).pick().getVideoServerUrl().split("//")[1]);
        try {
            Thread t = new Thread(new Runnable(){
                @Override
                public void run(){
                    try{
                        // run方法具体重写
                        while (true) {
                            try {
                                WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
                                DeviceAlarmWebsocketConfig deviceStatusWebsocketConfig = new DeviceAlarmWebsocketConfig();
                                webSocketContainer.connectToServer(deviceStatusWebsocketConfig, new URI(deviceStatusWsUrl2));
                                return;
                            }catch (Exception e1) {
                                log.error("", e1);
                            }
                            try {
                                Thread.sleep(300 * 1000);
                            } catch (Exception e2) {
                                log.error("", e2);
                            }
                        }
                    }catch (Exception e2){
                        log.error("",e2);
                    }
                }});
            t.start();
        }catch (Exception e){
            log.error("",e);
        }
    }
    @OnOpen
    public void onOpen(Session session) {
        log.info("正在报警重试的次数:{}",retryNum++);
        log.info("[websocket->{}] 报警订阅连接成功",deviceStatusWsUrl2);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("[websocket->{}] 报警订阅收到消息={}",deviceStatusWsUrl2,message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        Gb28181Service gb28181Service = SpringUtil.getBean(Gb28181ServiceImpl.class);
        boolean bol = gb28181Service.uploadAlarm(jsonObject);
        log.info("设备收到报警订阅{}信息,处理结果为:{},报警值为:{}",bol,jsonObject.getString("AlarmDescription"));
    }

    @OnClose
    public void onClose() {
        log.info("[websocket->{}] 退出连接",deviceStatusWsUrl2);
        log.info("报警订阅客户端已关闭!");
        log.info("开始尝试重新连接报警订阅(次数->{})...",retryNum);
        Boolean closeRetryOk = false;
        while (true) {
            try {
                WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
                DeviceAlarmWebsocketConfig deviceStatusWebsocketConfig = new DeviceAlarmWebsocketConfig();
                webSocketContainer.connectToServer(deviceStatusWebsocketConfig, new URI(deviceStatusWsUrl2));
                retryNum++;
                closeRetryOk = true;
            } catch (Exception e) {
                closeRetryOk =false;
                log.info("报警订阅重新连接失败,请检查网络!");
            }
            if(closeRetryOk==true) {
                break;
            }else {
                try {
                    Thread.sleep(300 * 1000);
                } catch (Exception e2) {
                    log.error("", e2);
                }
            }

        }

    }

    @OnError
    public void onError(Throwable ex) {
        log.error("[websocket->{}] 连接错误={}",deviceStatusWsUrl2,ex.getMessage());
        log.error("报警订阅websocket即将断开连接!");
        boolean errorRetryOk = false;
        while (true) {
            try {
                log.info("客户端已关闭!");
                log.info("开始尝试重新报警订阅连接(次数->{})...", retryNum);
                WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
                DeviceAlarmWebsocketConfig deviceStatusWebsocketConfig = new DeviceAlarmWebsocketConfig();
                webSocketContainer.connectToServer(deviceStatusWebsocketConfig, new URI(deviceStatusWsUrl2));
                retryNum++;
                errorRetryOk =true;
            } catch (Exception e) {
                errorRetryOk =false;
                log.info("重新启动报警订阅websocket连接失败!");
            }
            if(errorRetryOk==true) {
                break;
            }else {
                try {
                    Thread.sleep(300 * 1000);
                } catch (Exception e2) {
                    log.error("", e2);
                }
            }
        }
    }
}
